﻿using Main.UI;
using Main.UI.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WeifenLuo.WinFormsUI.Docking;

namespace Main.Engine
{
    partial class WindowManager : IWindowManager
    {
        static WindowManager()
        {
            Instance = new WindowManager();
        }

        internal static IWindowManager Instance { get; private set; }
        private Dictionary<Type, IToolWindow> TOOL_WINDOWS = new Dictionary<Type, IToolWindow>();

        private WindowManager()
        {
            LocateToolWindows();

        }


        private void LocateToolWindows()
        {
            Type TypeOfToolWindow = typeof(IToolWindow);
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type t in assembly.GetTypes().Where(o => TypeOfToolWindow.IsAssignableFrom(o)))
                {
                    if (t.IsClass && !t.IsAbstract)
                    {
                        ConstructorInfo cinfo = t.GetConstructor(Type.EmptyTypes);
                        if (cinfo != null && cinfo.IsPublic)
                        {
                            IToolWindow o = (IToolWindow) cinfo.Invoke(null);
                            if (o is DockContent)
                            {
                                ((DockContent)o).DockPanel = Console.Instance.MainDock;
                            }
                                
                            foreach (Type iFace in t.GetInterfaces().Where( w => TypeOfToolWindow.IsAssignableFrom(w)))
                            {
                                if (iFace == TypeOfToolWindow) continue;
                                if (TOOL_WINDOWS.ContainsKey(iFace))
                                    continue;
                                TOOL_WINDOWS.Add(iFace, o);
                            }
                        }
                    }
                }
            }
        }
    }
}
